<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" top="0" width="720px" append-to-body>
		<div class="import_dialog_wrapper">
			<div class="tips">
				<h2>操作说明：</h2>
				<p>
					1、下载
					<span @click="handleDownTemplate()">Excel格式模板</span>
					文件。
				</p>
				<p>2、请注意格式要求，支持单选题、多选题、判断题等题型。</p>
				<p>3、请确保EXCEL文件版本为97-2003，并请勿删除（或新增）模板文件中的列，确保文件能顺利解析。</p>
				<p>4、请核对填写日期单元格，其属性为“文本”。</p>
				<p>5、模板数据请勿删除。</p>
			</div>
			<el-form v-bind="formConfig" :model="formData" :rules="formRules" label-width="80px">
				<el-form-item label="所属题库" prop="bankId">
					<el-select v-model="formData.bankId" placeholder="请选择所属题库" style="width: 100%">
						<el-option v-for="(item, index) in list" :key="index" :label="item.name" :value="item.id">
							<h4>{{ item.name }}</h4>
							<p>{{ item.permission | bankPermissonFilter }}</p>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="导入附件" prop="attach">
					<el-upload v-bind="uploadConfig" :action="uploadAction" :data="uploadParams">
						<el-button slot="trigger" type="primary" v-show="!formData.attach">选择模板</el-button>
						<el-button type="primary" v-show="!!formData.attach" @click="handleReelect()">重新选择</el-button>
						<div slot="tip" class="info" v-if="!!formData.attach">
							<h4>{{ formData.attach?.name }}</h4>
							<el-button type="text" icon="el-icon-delete" @click="handleRemoveAttach()">删除</el-button>
						</div>
					</el-upload>
				</el-form-item>
			</el-form>
		</div>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="loading" @click="handleSubmitForm()">导入</el-button>
		</template>
	</el-dialog>
</template>

<script>
const baseUrl = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
export default {
	props: {
		value: { type: Boolean, default: false },
		list: { type: Array, default: () => [] }
	},
	data() {
		const Authorization = this.$session.get('token');
		const uploadValidator = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请选择导入试题附件'));
			} else {
				callback();
			}
		};
		return {
			loading: false,
			visible: this.value,
			dialogTitle: '导入试题',
			formConfig: { ref: 'form', size: 'medium' },
			formData: {},
			formRules: {
				bankId: [{ required: true, message: '请选择所属题库', trigger: 'change' }],
				attach: [{ required: true, validator: uploadValidator, trigger: 'change' }]
			},
			uploadAction: `${baseUrl}/testSubjects/import`,
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				accept: '.xls',
				autoUpload: false,
				showFileList: false,
				class: 'upload_template',
				headers: { Authorization },
				onChange: this.handleUploadChange,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload
			}
		};
	},
	computed: {
		uploadParams() {
			return { bankId: this.formData.bankId };
		}
	},
	filters: {
		bankPermissonFilter(input) {
			if (input === '1') {
				return '完全私有';
			} else if (input === '2') {
				return '只读共享';
			}
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
		}
	},
	methods: {
		//下载模板
		handleDownTemplate() {
			window.location.href = `${baseUrl}/testSubjects/down`;
		},

		//上传改变
		handleUploadChange(file, fileList) {
			if (file.status === 'ready') {
				this.$set(this.formData, 'attach', file.raw);
				this.$refs['form'].validateField('attach');
			}
		},

		handleBeforeUpload(file) {
			this.loading = true;
		},

		//移除上传附件
		handleRemoveAttach() {
			this.$refs['upload'].clearFiles();
			this.$delete(this.formData, 'attach');
		},

		//重新选择文件
		handleReelect() {
			this.handleRemoveAttach();
			this.$refs['upload'].$refs['upload-inner'].handleClick();
		},

		handleUploadSuccess(res, file, fileList) {
			this.loading = false;
			if (res.code === '0') {
				this.$message.success(res.msg);
				this.$emit('success');
				this.visible = false;
			}
		},

		handleSubmitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				this.$refs['upload'].submit();
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.import_dialog_wrapper {
	width: 100%;
	.tips {
		padding: 16px 16px 6px;
		border: solid 1px #ebeef5;
		background-color: #f5f7fa;
		margin-bottom: 24px;
		h2 {
			font-size: 16px;
			font-weight: 600;
			line-height: 1;
			margin-bottom: 16px;
			color: #606266;
		}
		p {
			display: flex;
			align-items: center;
			font-size: 14px;
			line-height: 1;
			margin-bottom: 10px;
			color: #909399;
			span {
				margin: 0 4px;
				cursor: pointer;
				font-weight: bold;
				color: var(--primary);
				&:hover {
					color: var(--primary-hover);
					text-decoration: underline;
				}
			}
		}
	}
}
.upload_template {
	display: flex;
	.info {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-left: 12px;
		overflow: hidden;
	}
}
</style>
